<template>
  <div class="accessory">
    <!-- 1、搜索区域 -->
    <div class="header">
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="exportTable">导出表格</el-button>
    </div>
    <!-- 2、表格区域展示视图数据 -->
    <div class="wrapper">
      <el-table :data="tableData" border ref="multipleTable" @row-click="handleRowClick" :row-key="getRowKey"
        @selection-change="handleSelectionChange" stripe style="width: 100%">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="equipment" label="设备号" show-overflow-tooltip
          :render-header="renderHeader"></el-table-column>
        <el-table-column prop="Name_of_PM_Planner_Group" label="PM计划者组名称" show-overflow-tooltip
          :render-header="renderHeader"></el-table-column>
        <el-table-column prop="Component_encoding" label="组件编码" show-overflow-tooltip :render-header="renderHeader">
          <template slot-scope="scope">
            <p style="text-decoration:underline;color:blue">{{ scope.row.Component_encoding }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="Code_material_description" label="编码物料描述" show-overflow-tooltip
          :render-header="renderHeader"></el-table-column>

        <el-table-column prop="Sealing_drawing" label="密封图纸" show-overflow-tooltip width="150px">
          <template slot-scope="scope">
            <img v-if="scope.row.Sealing_drawing" :src="scope.row.Sealing_drawing" alt="Image"
              style="width: 100%; height: auto;">
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="primary" @click="handleShow(scope.row)">详情</el-button> -->
            <el-button size="mini" type="danger" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
            <el-button size="mini" type="primary">
              <a :href="`#/goods?device_number=${scope.row.equipment}`">
                设备
              </a>
            </el-button>
            <el-button size="mini" type="success" @click="queryByComponentEncoding(scope.row.Component_encoding)">
              deepseek数据分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <el-button @click="toggleSelection(tableData)">全选</el-button>
      <el-button @click="toggleSelection()">反选</el-button>
    </div>
    <el-dialog title="配件信息" :visible.sync="showAccessoryInfoModal" width="30%" :before-close="handleClose">
      <el-table :data="getAccessoryInfoArray()" border>
        <el-table-column prop="title" label="属性"></el-table-column>
        <el-table-column prop="value" label="值"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAccessoryInfoModal = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" title="提示" width="30%">
      <p>后续接入deepseek统计查询结果，对查询结果进行分析</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 3、分页 -->

    <MyPagination :total="total" :pageSize="pageSize * 1" :currentPage="currentPage" @changePageNum="getPageNum"
      @changePageSize="changePageSize" />

    <!-- 添加弹窗 -->
    <AccessoryDialog ref="dialog" :title="title" :rowData="rowData" @changePage="getPage(1)" />
  </div>
</template>

<script>
import MyPagination from '@/components/MyPagination.vue'
import HeaderSearch from '@/components/HeaderSearch.vue'
import AccessoryDialog from './AccessoryDialog.vue'
import { export2Excel } from '@/common/js/util'
import { getAccessoryList, delAccessory } from '@/api/index.js'

export default {
  components: {
    MyPagination,
    AccessoryDialog
  },
  data() {
    return {
      showAccessoryInfoModal: false,
      deviceInfo: {},
      multipleSelection: [], //被勾选的数据

      columnMap: {},
      keyword: "",
      tableData: [],
      total: 10,
      pageSize: 10,  // 一般默认值设为1
      currentPage: 1,  //当前页，让哪一页高亮
      searchList: [],  // 搜索列表
      type: 1,  //1：查询所有商品列表的分页   2：查询搜索列表的分页
      title: '设备添加',   //弹窗标题
      rowData: {},  // 整行数据
      columns: [
        { title: 'PM计划者组名称', key: 'Name_of_PM_Planner_Group' },
        { title: '设备号', key: 'equipment' },
        { title: '抬头备注', key: 'Title_Remarks' },
        { title: '设备描述', key: 'Equipment_Description' },
        { title: '状态', key: 'state' },
        { title: '类别', key: 'category' },
        { title: '关键字', key: 'keyword' },
        { title: '计划工厂', key: 'Planned_Factory' },
        { title: '计划人员组', key: 'Planning_personnel_group' },
        { title: '设备种类', key: 'Equipment_type' },
        { title: '设备种类描述', key: 'Equipment_type_description' },
        { title: 'ABC标识', key: 'ABC_identification' },
        { title: '密封装机数量', key: 'Sealed_installation_quantity' },
        { title: '轴承装机数量', key: 'Number_of_installed_bearings' },
        { title: '密封供应商', key: 'Sealing_supplier' },
        { title: '备用制造商', key: 'Backup_manufacturer' },
        { title: '密封类型', key: 'Sealing_type_one' },
        { title: '密封型式', key: 'Sealing_type_two' },
        { title: '密封描述', key: 'Sealing_description' },
        { title: '冲洗方案', key: 'Rinse_plan' },
        { title: '组件编码', key: 'Component_encoding' },
        { title: '编码物料描述', key: 'Code_material_description' },
        { title: '含税单价元/套', key: 'Unit_price_including_tax_yuan' },
        { title: '库位', key: 'Warehouse_location' },
        { title: '库存数量', key: 'Inventory_quantity' },
        { title: '寄售数量', key: 'Consignment_quantity' },
        { title: '备注', key: 'remarks' },
        { title: '密封图纸', key: 'Sealing_drawing' }
      ],

      pageSizes: [10, 20, 50, 100, 500, 1000], // 可选的每页显示条数
      searchWords: {
        equipment: '',
        Name_of_PM_Planner_Group: '',
        Component_encoding: '',
        Code_material_description: '',

      },
      dialogVisible: false,
    }
  },
  // 生命周期函数
  created() {
    // this.columnMap = this.generateColumnMap(this.columns);

    if (location.href.includes('?equipment='))
      this.searchWords.equipment = location.href.split('?equipment=')[1];
    this.getAccessoryList(1) //调用
  },
  watch: {
    $route: function () {
      this.getAccessoryList(1)
    }
  },
  methods: {
    getAccessoryInfoArray() {
      return Object.entries(this.deviceInfo).map(([key, value]) => ({
        title: this.getColumnTitle(key),
        value: value
      }));
    },
    handleRowClick(row, event, column) {
      if (column.label !== '操作' && (column.label === '组件编码')) {
        this.handleShow(row, event, column);
      }
    },
    getColumnTitle(key) {
      const column = this.columns.find(col => col.key === key);
      return column ? column.title : key;
      // return column ? column.title : undefined;
    },
    //切换分页后，还保持全选状态
    getRowKey(row) {
      return row.id;
    },
    // 根据页码查询商品列表
    async getAccessoryList(pageNum) {
      try {
        if (location.href.includes('?biaos='))
          this.searchWords.biaos = location.href.split('?biaos=')[1];
        // else
        //   this.searchWords.biaos = '';
        const params = { page: pageNum, pageSize: this.pageSize, searchWords: this.searchWords };
        const res = await getAccessoryList(params);
        console.log("pamas", res);
        this.tableData = res.data;
        this.total = res.total;
        //this.pageSize = res.pageSize;
      } catch (error) {
        // console.log(error)
      }
    },
    async search() {
      this.getAccessoryList(1);
    },
    // 搜索商品
    // 父组件接收 分页子组件传过来的页码
    getPageNum(page) {
      this.currentPage = page;  //点击页码，让当前页码高亮
      console.log(page);
      if (this.type == 1) {
        this.getAccessoryList(page);  // 查询所有商品分页
      } else {
        // 搜索分页 ，切割数据  0,1,2  3,4,5  6,7,8   slice(,)  0,3  3,6  6,9
        // ((page-1)*3,page*3)
        this.tableData = this.searchList.slice((page - 1) * 3, page * 3);  //搜索完记得让type标记变为为2
      }
    },
    // 跳转到新页面去添加
    toAdd() {
      this.$router.push('/add-accessory');
      this.title = "设备添加";
    },
    // 弹窗 添加商品页面
    addDialog() {
      this.$refs.dialog.dialogVisible = true;
      this.title = "设备添加";
    },
    // 编辑
    handleEdit(index, row) {
      console.log('hell', index, row);
      this.$refs.dialog.dialogVisible = true; //显示弹窗
      this.title = "设备编辑";
      this.rowData = { ...row }; //{...row}：对象解构，用来每次都创建一个新对象
    },
    // 给子组件传值
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('你确定要删除设备吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {  // eslint-disable-line no-unused-vars
        // 删除商品，请求后台
        try {
          const res = await delAccessory({ id: row.id })
          console.log(res);
          if (res.status == 200) {
            this.getAccessoryList(1);  //更新列表，并展示第一页数据
            this.currentPage = 1;  //让页码在在第一页高亮
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
          }
        } catch (error) {
          console.log(error);
        }
      }).catch(() => {
        console.log('取消删除');
        this.$message({
          message: '已取消删除！',
          type: 'info'
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //全选和反选（对当前页数据）
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //为了让商品在添加或编辑后，刷新数据，并展示第一页数据时，让页码在在第一页高亮
    getPage(page) {
      this.currentPage = page;
    },

    exportTable() {
      // export2Excel('表头', '需要导出的数据')
      export2Excel(this.columns, this.tableData, '设备清册')
    },
    changePageSize(pageSize) { // 修改
      this.pageSize = pageSize;
      console.log('aa', this.pageSize);
      this.getAccessoryList(this.pageNum);
    },
    handleClose(done) {
      this.showAccessoryInfoModal = false;
      done();
    },
    handleShow(row) {
      this.deviceInfo = row;
      this.showAccessoryInfoModal = true;
      console.log('showAccessoryInfoModal:', this.showAccessoryInfoModal);
    },
    renderHeader(createElement, { column }) {
      return createElement('div', [
        createElement('div', { domProps: { innerHTML: column.label } }),
        createElement(HeaderSearch, {
          props: {
            searchWord: this.searchWords[column.property]
          },
          on: {
            change: (val) => {
              this.searchWords[column.property] = val;
            }
          }
        })
      ])
    },
    queryByComponentEncoding(componentEncoding) {
      // 在这里调用查询接口，并根据组件编码进行过滤
      // 例如：
      this.searchWords.Component_encoding = componentEncoding;
      this.getAccessoryList(1);
      // 弹出对话框
      // this.$message({
      //   message: '后续接入deepseek统计查询结果，对查询结果进行分析',
      //   type: 'success'
      // });
      this.dialogVisible = true;
    }


  }
}
</script>
<style lang="less" scoped>
.accessory {
  padding: 20px;

  .header {
    display: flex; //弹性布局
    justify-content: flex-end;

    button {
      margin-left: 20px;
    }
  }

  .wrapper {
    padding: 20px 0;
    overflow-x: auto;
    /* 添加横向滚动条 */
  }

  .underline-column .cell {
    text-decoration: underline !important;
  }
}
</style>
